package com.tcode.provider.controller;


import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import com.tcode.provider.entity.Info;
import com.tcode.provider.entity.User;
import com.tcode.provider.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;


import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2019-10-23
 */
@RestController
//@RequestMapping("")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DiscoveryClient client;
    @RequestMapping("/users/login")
//    @HystrixCommand(fallbackMethod = "loginHystrix")//熔断器
    public String login(@RequestBody User user, Info info) throws Exception {
        System.out.println(info);
        System.out.println("生产者 控制层");
        System.out.println(user);
        List<ServiceInstance> list = client.getInstances("provider");
        System.out.println("list:  "+list);
        for(ServiceInstance instance:list){

            System.out.println(instance.getHost()+":"+instance.getPort());
        }



//        System.out.println(user);
        User user1=iUserService.getByName(user.getUname());

        System.out.println(user1);
        if(user1==null){
            return "登录失败";
        }else{
//            调用方法把user对象存入redis
//            preUser(user1);

            return "登录成功";

        }

    }
    public String loginHystrix(@RequestBody User user){
        System.out.println("执行熔断器");
        return "执行熔断，服务器出错，正在处理";
    }
// 存入redis
//    public void preUser(User user){
//        ValueOperations<String,Object> operations=redisTemplate.opsForValue();
//        operations.set("user",user,20, TimeUnit.MINUTES);
//
//    }

//    @RequestMapping("/users/upload")
//    public String upload(@RequestBody String filePath){
//        System.out.println("文件地址存入数据库 filepath:"+filePath);
//        ValueOperations<String,Object> operations=redisTemplate.opsForValue();
//        User user1= (User) operations.get("user");
//        iUserService.insertImg(filePath,user1.getUname());
//        System.out.println("filePath="+filePath+"----------  name="+user1.getUname());
//        return null;
//    }


}
